package com.abc.easyclaim;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.abc.bean.Case;
import com.abc.bean.Record;
import com.abc.db.DBManager;
import com.abc.tool.StringTool;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class RecordSound extends Activity{

	U2UpdateReceiver u2ur;          //界面更新Intent的接收者
	private ImageButton recordButton;               //录音按钮
	private ImageButton stopRecordButton;           //停止录音按钮
	private Button returnButton;          //返回按钮
	private Button advanceButton;        //前进到播放界面按钮
	private TextView recordTimeTextView;        //录音时间长度显示文本
	private int itemid;           //list中被选中项的序号
	private static int currentPlay=-1;         //后台正在播放的录音文件的序号       
	private Date curDate;          //录音日期时间
	private MainApplication appCurrentPlay;              //全局变量
	private int record_time=0;  //记录文件录制时间长度
	private String soundFileName;            //要录音的默认文件路径
	private String filesPath;
    private List<Record> records=new ArrayList<Record>();         //录音集合
    private DBManager dbManager;           //数据库操作管理器  
    private Case caze;
    private Intent intent;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recordsound);
		dbManager=new DBManager(getBaseContext());
		caze = dbManager.queryCase(MainApplication.getCurrentCaseId());
		filesPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/"+caze.getName()+"/records";  //存储录音文件的文件夹路径
		
		appCurrentPlay=(MainApplication)getApplication();          //全局变量
		//标题栏的布局
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.record_titlebar); 
		//创建界面更新Intent接收者
		u2ur=new U2UpdateReceiver(this);
		//获取按钮组件
		recordButton=(ImageButton)findViewById(R.id.record);
		stopRecordButton=(ImageButton)findViewById(R.id.stop);
		returnButton=(Button)findViewById(R.id.return_record);
		advanceButton=(Button)findViewById(R.id.advance);
		
		initConpoment();             //初始化操作
		
		//为按钮添加监听器
		recordButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("record_u2ur.status="+u2ur.status);
				//若当前为录音状态
				if (u2ur.status==Constant.STATUS_RECORD) {
					Intent intent=new Intent(Constant.RECORD_CONTROL);
					intent.putExtra("cmd", Constant.COMMAND_PAUSERECORD); 
					//发出暂停命令
					RecordSound.this.sendBroadcast(intent); 
				}
				//若当前为停止录音状态
				else if (u2ur.status==Constant.STATUS_STOPRECORD) {
					File recordFolder=new File(filesPath);         //创建保存records的文件夹
					if (!recordFolder.exists()) {
						recordFolder.mkdirs();
					}
					//创建保存录音的音频文件
					soundFileName=filesPath+"/record0.amr";
					Intent intent=new Intent(Constant.RECORD_CONTROL);
					intent.putExtra("cmd", Constant.COMMAND_RECORD);
					intent.putExtra("defaultNum", 0);
					intent.putExtra("soundFileName", soundFileName);
					//发出录音命令
					RecordSound.this.sendBroadcast(intent); 
				}
				//若当前为暂停录音状态
				else if (u2ur.status==Constant.STATUS_PAUSERECORD) {
					Intent intent=new Intent(Constant.RECORD_CONTROL);
					intent.putExtra("cmd", Constant.COMMAND_RECORD); 
					//发出继续录音命令
					RecordSound.this.sendBroadcast(intent); 
				}
			}
		});
		stopRecordButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("stop_u2ur.status="+u2ur.status);
				//按下停止按钮后广播出去停止命令的Intent					
				Intent intent=new Intent(Constant.RECORD_CONTROL);
				intent.putExtra("cmd", Constant.COMMAND_STOPRECORD);
				RecordSound.this.sendBroadcast(intent);
				
				curDate=new Date(System.currentTimeMillis());//获取当前时间    
				//跳转到录音描述界面，填写描述和命名
				Intent intent1=new Intent(RecordSound.this,RecordDescription.class);
				Bundle bundle=new Bundle();
				//由默认文件名得到默认文件序号
				bundle.putString("recordname", "");   //传入默认的录音文件名
				ArrayList<String> recordnameList=new ArrayList<String>();
				for (int i = 0; i < records.size(); i++) {
					recordnameList.add(i, records.get(i).getTitle());
				}
				bundle.putStringArrayList("recordnames", recordnameList);  //传入所有音频文件名用来判断重命名
				bundle.putBoolean("reedit", false);         //是否是重新编辑的标记
				String record_time_string=recordTimeTextView.getText().toString().trim();
				record_time=getRecordTime(record_time_string);           //得到录音长度
				bundle.putInt("record_time", record_time);   //文件时长
				intent1.putExtras(bundle);
				startActivityForResult(intent1, 4);
				record_time=0;   //初始化
			}
		});
		returnButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				appCurrentPlay.setState(currentPlay);
				//stopService(intent);
				
				finish();
			}
		});
		advanceButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (currentPlay!=-1) {             //后台在播放
					Intent intent=new Intent(RecordSound.this,PlaySound.class);
					Bundle bundle=new Bundle();
					intent.putExtras(bundle);
					startActivity(intent);
					finish();
				}
				else if (records.size()>0){                //存在文件
					Intent intent=new Intent(RecordSound.this,PlaySound.class);
			    	appCurrentPlay.setState(0);
			    	Bundle bundle=new Bundle();
					intent.putExtras(bundle);
			    	startActivity(intent);
			    	finish();
				}
				else {
					Toast.makeText(RecordSound.this, "没有可以播放的文件，请先录制！", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		//动态注册接收播放、暂停、停止状态更新Intent的UIUpdateReceiver
        IntentFilter filter=new IntentFilter();
		filter.addAction(Constant.RECORD_UPDATE);
		this.registerReceiver(u2ur, filter);
		intent=new Intent(this,MyRecordService.class);
		//发出启动后台Service的Intent
		this.startService(intent);	
				
	}
	
	//初始化组件函数
	private void initConpoment(){
		//获取TextView组件
		recordTimeTextView=(TextView)findViewById(R.id.time);
		currentPlay=appCurrentPlay.getState();  
		//显示已录制片段列表
		showList();
	}

	private void showList() {
		records=dbManager.queryRecords(MainApplication.getCurrentCaseId());
		List<Map<String,Object>> listItems=new ArrayList<Map<String, Object>>();
		for(int j=0;j<records.size();j++)
		{
			Map<String, Object> listItem =new HashMap<String, Object>();
			listItem.put("name", records.get(j).getTitle());
			if (currentPlay==j) {
				listItem.put("showplaying", "后台正在播放该文件！");
			}
			else {
				listItem.put("showplaying", "");
			}
			listItem.put("long", getString(R.string.list_recordlong)+getRecordLong(records.get(j).getLength()));
			listItem.put("time", getString(R.string.list_recordtime)+StringTool.date2String(records.get(j).getDate(), "yyyy-MM-dd HH:mm:ss"));
			listItem.put("description", records.get(j).getDescription());
			listItem.put("path", getString(R.string.list_recordpath)+records.get(j).getPath());
			listItems.add(listItem);
		}
		//创建一个SimpleAdapter
		SimpleAdapter simpleAdapter=new SimpleAdapter(this, listItems,R.layout.simple_item,
				new String[] {"name","showplaying","long","time","description","path"},
				new int[] {R.id.list_record_name,R.id.list_showplaying,R.id.list_record_long,R.id.list_record_time,R.id.list_record_description,R.id.list_record_path});
		ListView list=(ListView)findViewById(R.id.mylist);
		//为ListView设置Adapter
		list.setAdapter(simpleAdapter);
		registerForContextMenu(list);   //为列表注册上下文菜单
		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				System.out.println(arg2);
				itemid=arg2;              //传递第几项被选中
				return false;
			}			
		});		
	}
	
	//创建上下文菜单时触发此方法
    @Override
 	public void onCreateContextMenu(ContextMenu menu, View v,
 			ContextMenuInfo menuInfo) {
 		// TODO Auto-generated method stub
     	getMenuInflater().inflate(R.menu.popup_menu, menu);       //添加菜单布局
 		super.onCreateContextMenu(menu, v, menuInfo);
 	}
	
    //上下文菜单的菜单项被单击时触发该方法
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		if (itemId == R.id.play) {
			playRecord(itemid);
		} 
		else if (itemId == R.id.reedit) {
			reeditRecord(itemid);
		} 
		else if (itemId == R.id.delete) {
			deleteRecord(itemid);
		} 
		else if (itemId == R.id.exit) {
		}
		return super.onContextItemSelected(item);
	}
    
    //播放选中音频文件函数
    public void playRecord(int itemid){
    	//跳转到播放界面
    	Intent intent=new Intent(RecordSound.this,PlaySound.class);
    	Bundle bundle=new Bundle();
		intent.putExtras(bundle);
    	startActivity(intent);
    	appCurrentPlay.setState(itemid);
    	finish();
    }
	
    //重命名选中音频文件函数
    public void reeditRecord(final int itemid){
    	if (currentPlay != itemid) {
    		Intent intent =new Intent(RecordSound.this,RecordDescription.class);
        	Bundle bundle=new Bundle();
        	bundle.putString("recordname", records.get(itemid).getTitle().split("\\.amr")[0]);   //传入录音文件名
        	ArrayList<String> recordnameList=new ArrayList<String>();
    		for (int i = 0; i < records.size(); i++) {
    			recordnameList.add(i, records.get(i).getTitle());
    		}
    		bundle.putStringArrayList("recordnames", recordnameList);  //传入所有音频文件名用来判断重命名
    		bundle.putBoolean("reedit", true);         //是否是重新编辑的标记
    		bundle.putString("description", records.get(itemid).getDescription()); //传入描述内容
    		bundle.putInt("record_time", records.get(itemid).getLength());   //文件时长
    		intent.putExtras(bundle);
    		startActivityForResult(intent, 5);
		}
    	else {
			Toast.makeText(this, "正在播放该文件，不能编辑", Toast.LENGTH_SHORT).show();
		}
    }
    
    //删除选中音频文件函数
  	public void deleteRecord(int itemid){
  		if (currentPlay != itemid) {
  		    //从数据库中删除
  			dbManager.deleteRecord(records.get(itemid));
  			//删除SDK卡中的本地文件
  			File f=new File(filesPath+"/"+records.get(itemid).getTitle());
  			f.delete();
  			records=dbManager.queryRecords(MainApplication.getCurrentCaseId());              //更新列表
  			showList();              //显示列表
  			if (currentPlay>itemid) {
  				currentPlay--;
  				appCurrentPlay.setState(currentPlay);
			}
		}
  	    else {
			Toast.makeText(this, "正在播放该文件，不能删除！", Toast.LENGTH_SHORT).show();
		}
  	}
  	
  @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
	  if (resultCode==40) {
			//接收返回的数据
			String descriptionString=data.getStringExtra("description");
			String recordNameString=data.getStringExtra("recordName");
			System.out.println("recordNameString="+recordNameString);
			Boolean reedit=data.getBooleanExtra("reedit", false);
			record_time=data.getIntExtra("record_time", 0);
			System.out.println("return_record_time="+record_time);
			data.getExtras().remove("description");
			data.getExtras().remove("recordName");
			data.getExtras().remove("reedit");
			data.getExtras().remove("record_time");
			//不是重新编辑
	          if (!reedit) {
	          	//addDatabase();           
	          	//添加新数据到数据库中
	          	Record record=new Record();
	          	record.setId(records.size()>0?(records.get(records.size()-1).getId()+1):0);
	          	record.setTitle(recordNameString+".amr");
	          	record.setDescription(descriptionString);
	          	record.setDate(curDate);
	          	record.setPath(filesPath);
	          	record.setLength(record_time);
	          	record.setCaseId(MainApplication.getCurrentCaseId());
	          	dbManager.addRecord(record);
	          	//修改路径下的文件名
	          	String newPath=filesPath+"/"+recordNameString+".amr";            //获取新的路径
	          	soundFileName=filesPath+"/record0.amr";
	          	System.out.println("soundFileName"+soundFileName);
	          	File soundFiles=new File(soundFileName);
	          	soundFiles.renameTo(new File(newPath));
	          	//更新显示列表
	          	records=dbManager.queryRecords(MainApplication.getCurrentCaseId());           
	  			showList();             //重新显示已录制片段列表
				}
           //重新编辑
			else {
				if (!recordNameString.equals(records.get(itemid).getTitle().split("\\.amr")[0])) {
					String newPath=filesPath+"/"+recordNameString+".amr";            //获取新的路径
				    File oldFile=new File(filesPath+"/"+records.get(itemid).getTitle());        //找到原文件
				    oldFile.renameTo(new File(newPath));    //根据新路径改变音频文件名		
				}
				//更新数据库
				records.get(itemid).setTitle(recordNameString+".amr");
				records.get(itemid).setDescription(descriptionString);
				dbManager.modifyRecord(records.get(itemid));
			    //更新列表
				records=dbManager.queryRecords(MainApplication.getCurrentCaseId());
			    //重新显示列表
			    showList();
			}	   
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
  
	//检查新生成的默认音频文件名与保存的文件名不重复
  	public int checkName(int number) {
  		int savenum=number;                 //用来保存number值
  		int length=0;                             //记录.amr为后缀音频文件的个数
  		List<String> filesName=new ArrayList<String>();          //存放所有音频文件的去后缀文件名
  		File[] fs=new File(filesPath).listFiles();
  		for (File f : fs) {
  			filesName.add(f.getName().split("\\.amr")[0]);
  			length++;
  		}
  		//遍访list查看新生成默认音频文件名是否已存在，若存在,number+1再检查，直到不重复时返回可以创建音频文件的默认文件名
  		while(true){                       
  			for(int i=0;i<length;i++)                       
  			{
  				if (filesName.get(i).equals("record"+number)) {
  					savenum=number;            //保存number值
  					number++;	               //number+1继续检查有没有重复
  					break;                    //跳出for循环
  				}
  				savenum=number;              //如果没有跳出for循环，说明都不重复，满足退出while循环条件
  			}
  			if (savenum==number) {
  				return number;	            //如果number与上次循环相比值没变，则说明没有命名重复退出检查循环
  			}
  		}	
  	}
  	
	//获取录制完成文件时长函数
    public String getRecordLong(int time) {
    	String result=null;
    	int hour=time/3600;
    	int minutes=(time-hour*3600)/60;
    	int seconds=time-hour*3600-minutes*60;
    	result=(hour>0?hour+getString(R.string.hour):"")+
    			minutes+getString(R.string.minutes)+ seconds+getString(R.string.seconds);
		return result;
	}
    
    //由0:00:00形式得到int型
    public int getRecordTime(String time){
    	int intTime=0;
    	int hour=Integer.parseInt(time.split("\\:")[0]);
    	int minutes=Integer.parseInt(time.split("\\:")[1]);
    	int seconds=Integer.parseInt(time.split("\\:")[2]);
    	intTime=hour*3600 + minutes*60 + seconds;
		return intTime;
    }
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		this.unregisterReceiver(u2ur);
		super.onDestroy();
	}

	
	
}
